﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml.XPath;
using UmbSearch2.Search;


namespace UmbSearch2.XSLT_Extensions
{
	public class Searcher
	{
		public static XPathNodeIterator GetSearchResult(string query, string searchFields, int searchStartNodeId, int misspelledWordsNodeId, string documentTypes)
		{
			string[] searchFieldsArray = searchFields.Split(',');
			
			ArrayList documentTypesList = new ArrayList();

			string[] temp = documentTypes.Split(',');
			for (int i = 0; i < temp.Length; i++)
			{
				documentTypesList.Add(temp[i].Trim());
			}

			// get all the results
			List<SearchResultItem> results = Search.Searcher.Search(query, searchFieldsArray, searchStartNodeId, misspelledWordsNodeId, documentTypesList);

			XDocument xdoc = new XDocument();
			XElement searchResultItems = new XElement("searchResultItems");
			xdoc.Add(searchResultItems);

			foreach (SearchResultItem result in results)
			{
				XElement searchResultItem =
					new XElement("node",
								 new XAttribute("id", result.Id),
								 new XAttribute("title", result.Title ?? ""),
								 new XElement("summary", new XCData(result.Summary ?? "")),
					             new XAttribute("objectType", result.ObjectType),
					             new XAttribute("createdDate", result.CreateDate ?? ""),
					             new XAttribute("documentType", result.DocumentType ?? ""),
					             new XAttribute("extension", result.Extension ?? ""),
					             new XAttribute("filePath", result.FilePath ?? ""));

				searchResultItems.Add(searchResultItem);
			}

			return xdoc.CreateNavigator().Select("/");
		}
	}
}